package cn.xy.base.server.controller.admapi;

import cn.hutool.core.collection.CollUtil;
import cn.xy.base.server.dto.SysPermissionAddDTO;
import cn.xy.base.server.dto.SysPermissionUpdateDTO;
import cn.xy.base.server.enums.RoleEnum;
import cn.xy.base.server.po.SysPermission;
import cn.xy.base.server.po.SysRole;
import cn.xy.base.server.service.SysAdminService;
import cn.xy.base.server.service.SysPermissionService;
import cn.xy.base.server.service.SysRoleService;
import cn.xy.base.server.vo.SysPermissionVO;
import cn.xy.base.server.web.AdminWebContext;
import cn.xy.base.server.web.security.PermissionService;
import cn.xy.commons.annotation.OperateLog;
import cn.xy.commons.annotation.RepeatSubmit;
import cn.xy.commons.constant.Consts;
import cn.xy.commons.core.Result;
import cn.xy.commons.util.StringUtil;
import com.rustic.server.vo.RusticAdminDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 表[sys_permission]对应的后台管理类
 *
 * @author auto
 */

@Slf4j
@RestController
@RequestMapping("/admapi/sys/permission")
@Api(tags = {"权限管理接口"})
public class SysPermissionAdminController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysAdminService sysAdminService;

    @ApiOperation(value = "获取登陆用户的权限列表")
    @GetMapping("/list")
    public Result<List<SysPermissionVO>> list(int rusticId) {
        // 要是有rusticId有，则使用乡村的管理权限
        if (rusticId > 0) {
            RusticAdminDetailVO rusticAdmin = sysAdminService.getRusticAdmin(AdminWebContext.getAdminId(), rusticId);
            return Result.data(rusticAdmin.getPermissionList());
        }
        SysRole sysRole = sysRoleService.getById(AdminWebContext.getRoleId());
        if (sysRole == null) {
            return Result.error("角色权限异常");
        }
        SysRole basicRole = sysRoleService.getById(RoleEnum.BASIC.getId());
        List<String> basicIdStrList = StringUtil.splitToList(basicRole.getPermissions(), Consts.COMMA);
        List<String> idStrList = StringUtil.splitToList(sysRole.getPermissions(), Consts.COMMA);
        // 使用Stream API计算交集
        List<String> commonIdsList = basicIdStrList.stream()
                .filter(idStrList::contains)
                .collect(Collectors.toList());
        List<Integer> idList = commonIdsList.stream().map(Integer::parseInt).collect(Collectors.toList());
        List<SysPermission> sysPermissionList = sysPermissionService.listBySortDesc(0, idList);
        List<SysPermissionVO> sysPermissionVOList = sysPermissionService.generateTree(sysPermissionList);
        return Result.data(sysPermissionVOList);
    }

    @ApiOperation(value = "权限树状列表")
    @GetMapping("/tree")
    @PreAuthorize("@validate.hasPermission('system-permission-list')")
    public Result<List<SysPermissionVO>> tree() {
        List<SysPermission> sysPermissionList = sysPermissionService.listBySortDesc(0);
        List<SysPermissionVO> sysPermissionVOList = sysPermissionService.generateTree(sysPermissionList);
        return Result.data(sysPermissionVOList);
    }

    @PostMapping("/add")
    @ApiOperation(value = "增加系统权限配置")
    @OperateLog(description = "增加系统权限配置")
    @PreAuthorize("@validate.hasPermission('system-permission-add')")
    @RepeatSubmit
    public Result<String> add(@RequestBody @Valid SysPermissionAddDTO sysPermissionAddDTO) {
        if (sysPermissionAddDTO.getKey().contains(PermissionService.SEPARATOR)) {
            return Result.error("key值中不允许出现字符：" + PermissionService.SEPARATOR);
        }
        SysPermission sysPermission = sysPermissionService.getByPath(sysPermissionAddDTO.getPath());
        if (sysPermission != null) {
            return Result.error("该权限路径已存在");
        }
        SysPermission keyExist = sysPermissionService.getByKey(sysPermissionAddDTO.getKey());
        if (keyExist != null) {
            return Result.error("key值已存在");
        }
        sysPermission = sysPermissionAddDTO.toSysPermission();
        sysPermissionService.save(sysPermission);
        // 将新增的权限赋给超级管理员
        sysRoleService.addPermission(RoleEnum.SUPER_ADMIN, sysPermission.getId());
        return Result.ok("添加成功");
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改系统权限配置")
    @OperateLog(description = "修改系统权限配置")
    @PreAuthorize("@validate.hasPermission('system-permission-update')")
    @RepeatSubmit
    public Result<String> update(@RequestBody @Valid SysPermissionUpdateDTO sysPermissionUpdateDTO) {
        if (sysPermissionUpdateDTO.getKey().contains(PermissionService.SEPARATOR)) {
            return Result.error("key值中不允许出现字符：" + PermissionService.SEPARATOR);
        }
        SysPermission sysPermission = sysPermissionService.getById(sysPermissionUpdateDTO.getId());
        if (sysPermission == null) {
            return Result.error(SysPermissionService.PERMISSION_NOT_EXIST);
        }
        SysPermission keyExist = sysPermissionService.getByKey(sysPermissionUpdateDTO.getKey());
        if (keyExist != null && !keyExist.getId().equals(sysPermission.getId())) {
            return Result.error("key值已存在");
        }
        sysPermissionService.updateById(sysPermissionUpdateDTO.toSysPermission());
        return Result.ok("修改成功");
    }

    /**
     * 删除权限
     *
     * @param id id
     * @return result
     */
    @ApiOperation(value = "删除权限")
    @DeleteMapping("/delete")
    @OperateLog(description = "删除系统权限配置")
    @PreAuthorize("@validate.hasPermission('system-permission-delete')")
    @RepeatSubmit
    public Result<String> delete(int id) {
        SysPermission sysPermission = sysPermissionService.getById(id);
        if (sysPermission == null) {
            return Result.error(SysPermissionService.PERMISSION_NOT_EXIST);
        }
        List<SysPermission> childrenList = sysPermissionService.listByParentId(id);
        List<Integer> idList = new ArrayList<>();
        if (CollUtil.isNotEmpty(childrenList)) {
            idList = childrenList.stream().map(SysPermission::getId).collect(Collectors.toList());
        }
        idList.add(id);
        sysPermissionService.removeByIds(idList);
        return Result.ok("删除成功");
    }

    @GetMapping("/detail")
    @ApiOperation(value = "获取系统权限配置详情")
    @PreAuthorize("@validate.hasPermission('system-permission-detail')")
    public Result<SysPermission> permissionInfo(int id) {
        if (id <= 0) {
            return Result.error(SysPermissionService.PERMISSION_NOT_EXIST);
        }
        SysPermission permission = sysPermissionService.getById(id);
        if (permission == null) {
            return Result.error(SysPermissionService.PERMISSION_NOT_EXIST);
        }
        return Result.data(permission);
    }

    @GetMapping("listJson")
    @ApiOperation(value = "获取权限列表（无分页）")
    public Result<List<SysPermission>> listJson() {
        List<SysPermission> permissionList = sysPermissionService.list();
        return Result.data(permissionList);
    }
}
